package com.chang.search.service.impl;
/*
 * @Author Changzhenxi
 * @Date 2024/6/4 9:42
 * @Description This is description of method
 */

import com.alibaba.fastjson.JSON;
import com.chang.common.to.SkuEsModel;
import com.chang.search.config.GulimallElasticSearchConfig;
import com.chang.search.constant.EsConstant;
import com.chang.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {


    private final RestHighLevelClient restHighLevelClient;

    public ProductSaveServiceImpl(RestHighLevelClient restHighLevelClient) {
        this.restHighLevelClient = restHighLevelClient;
    }

    @Override
    public Boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        // 保存到es
        // 1,在es中建立索引,创建映射关系

        // 2,在es中保存数据  BulkRequest bulkRequest, RequestOptions options
        BulkRequest bulkRequest = new BulkRequest();
        // 构造保存请求
        IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
        for (SkuEsModel skuEsModel : skuEsModels) {
            indexRequest.id(skuEsModel.getSkuId().toString());
            String jsonString = JSON.toJSONString(skuEsModel);
            indexRequest.source(jsonString, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
        // 如果存在批量错误,还可以直接用bulk.hasFailures();获取
        boolean finalStatus = !bulk.hasFailures();  // 保存数据时是否有错
        List<String> itemList = Arrays.stream(bulk.getItems()).map(item -> {
            return item.getId();
        }).toList();
        log.info("商品上架完成:{}" + itemList);

        return finalStatus;

    }
}
